package com.lujieni.nio.c1;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 粘包和半包的问题
 */
public class TestByteBufferExam {

    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI'm lugege\nHo".getBytes());
        split(source);
       // source.put("w are you\n".getBytes());
       // split(source);

    }

    private static void split(ByteBuffer source){
        source.flip(); //读模式
        for (int i = 0; i < source.limit(); i++) {
            if(source.get(i) == '\n'){
                int lenght = i - source.position() + 1 ;
                ByteBuffer target = ByteBuffer.allocate(lenght);
                for(int j = 0; j < lenght; j++){
                    target.put(source.get());
                }
                target.flip();
                System.out.println(StandardCharsets.UTF_8.decode(target).toString());
            }
        }
       source.compact();
    }

}
